package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.Community;
import com.lanju.entity.Contract;
import com.lanju.entity.House;
import com.lanju.entity.User;



@Repository
public class UserDao {

    private static final Log log = LogFactory.getLog(UserDao.class);

    @PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;

    public void persist(User transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(User persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public User merge(User detachedInstance) {
        try {
            User result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public User getById(String  id) {
        try {
            User instance = entityManager.find(User.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public Contract getContractList(String address){
        try {
        	StringBuffer sql=new StringBuffer();
        	sql.append(" from Contract where city+region+houseAddress='"+address+"'");
            Query query=entityManager.createQuery(sql.toString());
            return  (Contract) query.getSingleResult();
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
		
    }
    /** 根据 手机号码获取用户,  */
    @SuppressWarnings("unchecked")
	public User getByPhone(String phone) {
        try {
        	if(phone==null){
        		return null;
        	}
            Query query = entityManager.createQuery("from User where phone=?1 ").setParameter("1", phone);
            List<User> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByPhone fail",e);
            throw e;
        }
    }
    
    /** 根据 手机号码、密码  获取用户,  */
    @SuppressWarnings("unchecked")
	public User getByPhoneAndPassword(Map<String, Object> param) {
        try {
        	String phone = (String)param.get("phone");
        	String password = (String)param.get("password");
        	String flag = (String)param.get("flag");
        	if(phone==null){
        		return null;
        	}
        	Query query = null;
        	if(flag!=null && flag.length()>0){
            	query = entityManager.createQuery("from User where phone=?1  and password=?2 and flag=?3").setParameter(1,phone).setParameter(2, password).setParameter(3, Integer.parseInt(flag));
        	}else{
            	query = entityManager.createQuery("from User where phone=?1  and password=?2 ").setParameter(1,phone).setParameter(2, password);
        	}
            List<User> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByPhone fail",e);
            throw e;
        }
    }
    
    /** 根据 微信openId  获取用户,  */
    @SuppressWarnings("unchecked")
	public User getByOpenId(Map<String, Object> param) {
        try {
        	String openId = (String)param.get("openId");
        	if(openId==null){
        		return null;
        	}
            Query query = entityManager.createQuery("from User where openId=?1 ").setParameter(1,openId);
            List<User> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByOpenId fail",e);
            throw e;
        }
    }
    

    @SuppressWarnings("unchecked")
	public List<User> getList(User user, int pageSize, int offset) {
        try {
            StringBuffer sqld = new StringBuffer("from User s where 1=1 ");
            if(!StringUtils.isEmpty(user.getPhone())){
                sqld.append(" and s.phone like:n ");
             }
             if(!StringUtils.isEmpty(user.getNickName())){
                 sqld.append(" and s.nickName like:1 ");
              }
             if(!StringUtils.isEmpty(user.getSex())){
                 sqld.append(" and s.sex=?2 ");
              }
             if(!StringUtils.isEmpty(user.getFlag())){
                 sqld.append(" and s.flag=?3");
              }
             if(!StringUtils.isEmpty(user.getIdCard())){
                 sqld.append(" and s.idCard=?4 ");
              }
             if(!StringUtils.isEmpty(user.getJobName())){
                 sqld.append(" and s.jobName like:5 ");
              }
            Query query = entityManager.createQuery(sqld.toString()).setFirstResult(offset).setMaxResults(pageSize);
            if(!StringUtils.isEmpty(user.getPhone())){
                query.setParameter("n", "%"+user.getPhone()+"%");
            }
            if(!StringUtils.isEmpty(user.getNickName())){
                query.setParameter("1", "%"+user.getNickName()+"%");
            }
            if(!StringUtils.isEmpty(user.getSex())){
                query.setParameter("2", user.getSex());
            }
            if(!StringUtils.isEmpty(user.getFlag())){
                query.setParameter("3", user.getFlag());
            }
            if(!StringUtils.isEmpty(user.getIdCard())){
                query.setParameter("4", user.getIdCard());
            }
           if(!StringUtils.isEmpty(user.getJobName())){
               query.setParameter("5", "%"+user.getJobName()+"%");
           }
            return query.getResultList();
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return null;
    }
    
    public long getListCount(User user) {
        try {
            StringBuffer sqld = new StringBuffer("select count(*) from User s where 1=1 ");
            if(!StringUtils.isEmpty(user.getPhone())){
               sqld.append(" and s.phone like:n ");
            }
            if(!StringUtils.isEmpty(user.getNickName())){
                sqld.append(" and s.nickName like:1 ");
             }
            if(!StringUtils.isEmpty(user.getSex())){
                sqld.append(" and s.sex=?2 ");
             }
            if(!StringUtils.isEmpty(user.getFlag())){
                sqld.append(" and s.flag=?3");
             }
            if(!StringUtils.isEmpty(user.getIdCard())){
                sqld.append(" and s.idCard=?4 ");
             }
            if(!StringUtils.isEmpty(user.getJobName())){
                sqld.append(" and s.jobName like:5 ");
             }
            
            Query query = entityManager.createQuery(sqld.toString());
            
             if(!StringUtils.isEmpty(user.getPhone())){
                 query.setParameter("n", "%"+user.getPhone()+"%");
             }
             if(!StringUtils.isEmpty(user.getNickName())){
                 query.setParameter("1", "%"+user.getNickName()+"%");
             }
             if(!StringUtils.isEmpty(user.getSex())){
                 query.setParameter("2", user.getSex());
             }
             if(!StringUtils.isEmpty(user.getFlag())){
                 query.setParameter("3", user.getFlag());
             }
             if(!StringUtils.isEmpty(user.getIdCard())){
                 query.setParameter("4", user.getIdCard());
             }
            if(!StringUtils.isEmpty(user.getJobName())){
                query.setParameter("5", "%"+user.getJobName()+"%");
            }
            return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return 0;
    }


    public List<User> getAllUser(Map<String,Object> param){
    	StringBuffer sql=new StringBuffer();
    	List<User> list=null;
		try {
			sql.append("from User where  flag="+Integer.valueOf(param.get("flag").toString()));
			sql.append(" and status=1 ");
			if(!StringUtils.isEmpty(param.get("searchText"))){
				sql.append(" and (phone like '%"+param.get("searchText").toString()+"%' ");
				sql.append(" or realName like '%"+param.get("searchText").toString()+"%' ");
				sql.append(" or nickName like '%"+param.get("searchText").toString()+"%' ");
				if(!StringUtils.isEmpty(param.get("userId"))){
					sql.append(" or userId in ("+param.get("userId").toString()+") ");
				}
				sql.append(")");
			}
			Query query=entityManager.createQuery(sql.toString());
			list = query.getResultList();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return list;
    }
    
    public List<House> getAllHouseList(Map<String,Object> param){
    	StringBuffer sql=new StringBuffer();
    	List<House> list=null;
		try {
			sql.append(" from House where  1=1 ");
			if(!StringUtils.isEmpty(param.get("searchText"))){
				sql.append(" and (houseName like '%"+param.get("searchText").toString()+"%' ");
				if(!StringUtils.isEmpty(param.get("community_id"))){
					sql.append(" or community_id in ("+param.get("community_id").toString()+") ");
				}
				sql.append(")");
			}
			Query query=entityManager.createQuery(sql.toString());
			list = query.getResultList();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return list;
    }
	public List<Community> getAreaCommunityList(Map<String, Object> param){
		try {
			StringBuffer sql=new StringBuffer();
			sql.append("select t.community_id as community_id from Community t where 1=1 ");
			if(!StringUtils.isEmpty(param.get("searchText"))){
				sql.append(" and community_name like '%"+param.get("searchText").toString()+"%'");
			}
			Query query=entityManager.createQuery(sql.toString());
			List<Community> list=query.getResultList();
			return list;
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 查询接收支付信息的人员
	 * @param param
	 * @return
	 */
    public List<User> getSendMessageUser(Map<String,Object> param){
    	StringBuffer sql=new StringBuffer();
    	List<User> list=null;
		try {
			sql.append("from User where reviceType like '%"+param.get("reviceType").toString()+"%'");
			Query query=entityManager.createQuery(sql.toString());
			list = query.getResultList();
            if(list!=null && list.size()>0){
                return list;
            }else{
                return null;
            }
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return list;
    }
    
    public void updateUserInfo(User user){
    	try {
			entityManager.merge(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
